#include "main.h"
#include "dma.h"
#include "usart.h"
#include "gpio.h"
#include "app_rtthread.h"
#include "app_key.h"
#include "app_oled.h"
#include "app_w5500.h"

KEY_INFO key1=INIT_KEY1;
KEY_INFO key2=INIT_KEY2;
KEY_INFO key3=INIT_KEY3;

void key_init(void)
{
	GPIO_InitTypeDef GPIO_InitStruct = {0};

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();
  __HAL_RCC_GPIOC_CLK_ENABLE();
//	uint8_t i=0;
//	for(i=0;i<3;i++)
//	{
//		key[i] = INIT_KEY;
//	}
	
	GPIO_InitStruct.Pin = key1.Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_PULLUP;
  HAL_GPIO_Init(key1.GPIO, &GPIO_InitStruct);
	
	GPIO_InitStruct.Pin = key2.Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_PULLUP;
  HAL_GPIO_Init(key2.GPIO, &GPIO_InitStruct);
	
	GPIO_InitStruct.Pin = key3.Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_PULLUP;
  HAL_GPIO_Init(key3.GPIO, &GPIO_InitStruct);
}

void key_scan(void)
{
	if(READ_KEY(key1.GPIO,key1.Pin) == KEY_DOWN)
	{
		key1.count++;
		key1.status = KEY_NONE;
	}else
	{
		if(key1.count>KEY_COUNT_MIN)key1.status = KEY_SHROT;

		if(key1.count>KEY_COUNT_MAX)key1.status = KEY_LONG;

		if(key1.count>KEY_COUNT_MIN)
		{
			key_action(key1.num,key1.status);
		}
		key1.count=0;
	}
	
	if(READ_KEY(key2.GPIO,key2.Pin) == KEY_DOWN)
	{
		key2.count++;
		key2.status = KEY_NONE;
	}else
	{
		if(key2.count>KEY_COUNT_MIN)key2.status = KEY_SHROT;

		if(key2.count>KEY_COUNT_MAX)key2.status = KEY_LONG;

		if(key2.count>KEY_COUNT_MIN)
		{
			key_action(key2.num,key2.status);
		}
		key2.count=0;
	}
	
	if(READ_KEY(key3.GPIO,key3.Pin) == KEY_DOWN)
	{
		key3.count++;
		key3.status = KEY_NONE;
	}else
	{
		if(key3.count>KEY_COUNT_MIN)key3.status = KEY_SHROT;

		if(key3.count>KEY_COUNT_MAX)key3.status = KEY_LONG;

		if(key3.count>KEY_COUNT_MIN)
		{
			key_action(key3.num,key3.status);
		}
		key3.count=0;
	}	
}
void key_action(uint8_t num,uint8_t status)
{
	printf("[%d]:key:%d:%d\n",(int)rt_tick_get(),num,status);
	EA0;
	switch(num)
	{
		case 1:
			oled_show1(); 
			break;
		case 3:
			oled_show2();
			break;
		case 2:
			oled_show1();
			break;
	}
	EA1;
}



